package br.com.casablanca.viewbean;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import br.com.casablanca.dto.LoginDTO;
import br.com.casablanca.exception.RegraNegocioException;
import br.com.casablanca.services.LoginService;
import br.com.casablanca.utils.CasablancaUtils;


public class LoginBean {  
    
	private String usuario;
	private String senha;
	
	public String login() {
		FacesContext context = FacesContext.getCurrentInstance();
		try {
			LoginDTO user = new LoginService().valida(usuario, CasablancaUtils.encripta(senha));
			HttpSession session = (HttpSession) context.getExternalContext().getSession(true);
			session.setAttribute("currentUser", user);
			SkinBean sk = (SkinBean) session.getAttribute("skinBean");
			sk.setSkin(user.getSkin());
		} catch (RegraNegocioException e) {
			context.addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), e.getMessage()));
			return "login";
		} catch (Exception e) {
			return CasablancaUtils.trataErro(context, e);
		}
		return "home";
	}

	public String logout() {            
	    FacesContext fc = FacesContext.getCurrentInstance();    
	    HttpSession session = (HttpSession)fc.getExternalContext().getSession(false);    
	    session.invalidate();     
	    return "login";     
	} 
	
	public String getUsuario() {
		return usuario;
	}
	public void setUsuario(String usuario) {
		this.usuario = usuario;
	}
	public String getSenha() {
		return senha;
	}
	public void setSenha(String senha) {
		this.senha = senha;
	}
}
